import { loginAPI } from '@/api/user' // 导入用户登录API
// import { TOKEN_KEY } from '@/constants/KEY'
import { getToken, removeToken, setToken } from '@/utils/auth' // 导入token操作函数

export default {
  namespaced: true, // 启用命名空间
  state: () => {
    return {
      token: getToken() || '' // 优先从本地取token
    }
  },
  mutations: {
    // 设置token的mutation
    setToken(state, token) {
      state.token = token
      setToken(token)
    },

    // 清除用户信息的mutation
    clearUserInfo(state) {
      state.token = ''
      removeToken() // 删除: removeToken()
    }
  },
  actions: {
    // 登录action
    async doLogin({ commit }, { username, password }) {
      try {
        const res = await loginAPI(username, password)
        if (res.code !== 10000) { // 修改此处的code判断
          throw new Error(res.message || '登录失败')
        }
        commit('setToken', res.data.token)
      } catch (error) {
        throw new Error(error.response?.data?.message || '登录失败')
      }
    }
  }
}

